package com.example.interceptor;

import com.example.model.entity.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是OPTIONS请求，直接放行
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }
        
        String path = request.getRequestURI();
        
        // 登录相关路径放行
        if (path.equals("/") || 
            path.equals("/login") || 
            path.startsWith("/api/backend/user/login") || 
            path.startsWith("/api/backend/user/register") || 
            path.startsWith("/static/")) {
            return true;
        }
        
        // 检查登录状态
        HttpSession session = request.getSession();
        UserInfo user = (UserInfo) session.getAttribute("user");
        if (user == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        
        return true;
    }
} 